import os
import subprocess
import requests

# Gogs API 配置
API_TOKEN = "eee09f0f3b758dd4ca71c9aa54e0a5c962061dbb"
GOGS_URL = "http://192.168.168.168:3000/api/v1"
USER_NAME = "wuyunbin"  # 替换为你的 Gogs 用户名
GOGS_BASE_URL = "http://192.168.168.168:3000"  # Gogs 的基础 URL

# todo 替换为你的本地仓库路径
# 扫描路径
SCAN_PATH = r"E:\IdeaProjects\robot\robot-server"

# 请求头
HEADERS = {
    "Authorization": f"token {API_TOKEN}",
    "Content-Type": "application/json",
}

def create_repo(repo_name):
    """在 Gogs 中创建仓库"""
    url = f"{GOGS_URL}/user/repos"
    data = {
        "name": repo_name,
        "description": "自动创建的仓库",
        "private": False,
    }
    response = requests.post(url, json=data, headers=HEADERS)
    if response.status_code == 201:
        print(f"仓库 {repo_name} 成功创建于 Gogs 中。")
        return True
    else:
        print(f"无法在 Gogs 中创建仓库 {repo_name}。错误: {response.status_code} - {response.text}")
        return False

def push_to_gogs(repo_path, repo_name):
    """将本地仓库推送到 Gogs"""
    os.chdir(repo_path)
    # 检查是否已经存在 remote
    result = subprocess.run(["git", "remote"], capture_output=True, text=True)
    if "gogs" in result.stdout:
        print(f"仓库 {repo_name} 已存在远程 'gogs'，跳过推送。")
        return

    # 添加 Gogs 作为远程仓库
    subprocess.run(["git", "remote", "add", "gogs", f"{GOGS_BASE_URL}/{USER_NAME}/{repo_name}.git"])
    # 推送所有分支
    subprocess.run(["git", "push", "gogs", "--all"])
    # 推送所有标签
    subprocess.run(["git", "push", "gogs", "--tags"])
    print(f"仓库 {repo_name} 成功推送到 Gogs。")

def setup_submodules(repo_path):
    """设置子模块关系"""
    os.chdir(repo_path)
    if not os.path.isfile(".gitmodules"):
        return

    print(f"正在处理仓库 {repo_path} 的子模块...")
    # 初始化子模块
    subprocess.run(["git", "submodule", "init"])
    subprocess.run(["git", "submodule", "update"])

    # 遍历子模块
    result = subprocess.run(["git", "config", "--file", ".gitmodules", "--get-regexp", "path"], capture_output=True, text=True)
    for line in result.stdout.splitlines():
        _, submodule_path = line.split()
        submodule_name = os.path.basename(submodule_path)
        submodule_gogs_url = f"{GOGS_BASE_URL}/{USER_NAME}/{submodule_name}.git"

        print(f"正在设置子模块 {submodule_name} 的远程仓库...")
        # 进入子模块目录
        os.chdir(submodule_path)
        # 检查是否已经存在 remote
        result = subprocess.run(["git", "remote"], capture_output=True, text=True)
        if "gogs" in result.stdout:
            print(f"子模块 {submodule_name} 已存在远程 'gogs'，跳过推送。")
        else:
            # 添加 Gogs 作为远程仓库
            subprocess.run(["git", "remote", "add", "gogs", submodule_gogs_url])
            # 推送所有分支
            subprocess.run(["git", "push", "gogs", "--all"])
            # 推送所有标签
            subprocess.run(["git", "push", "gogs", "--tags"])
            print(f"子模块 {submodule_name} 成功推送到 Gogs。")

        # 返回父仓库目录
        os.chdir(repo_path)

def main():
    # 查找所有包含 .git 目录的文件夹
    for root, dirs, files in os.walk(SCAN_PATH):
        if ".git" in dirs:
            repo_path = root
            repo_name = os.path.basename(repo_path)
            print(f"正在处理仓库: {repo_name}")

            # 检查仓库是否已存在于 Gogs
            response = requests.get(f"{GOGS_URL}/repos/{USER_NAME}/{repo_name}", headers=HEADERS)
            if response.status_code == 200:
                print(f"仓库 {repo_name} 已存在于 Gogs 中，跳过创建。")
            else:
                if create_repo(repo_name):
                    push_to_gogs(repo_path, repo_name)

            print("-" * 40)

    # 处理子模块关系
    print("正在设置子模块关系...")
    for root, dirs, files in os.walk(SCAN_PATH):
        if ".git" in dirs:
            repo_path = root
            setup_submodules(repo_path)
    print("子模块关系设置完成。")

if __name__ == "__main__":
    main()